// web/src/app/learn/(dashboard)/(routes)/teacher/courses/[courseId]/chapters/[chapterId]/_components/chapter-actions.tsx
'use client';
import React, {useState} from 'react';
import {Button} from "@/components/ui/button";
import {Trash} from "lucide-react";
import ConfirmModal from "@/components/learn/modals/confirm-modal";
import toast from "react-hot-toast";
import {useRouter} from "next/navigation";

interface Props {
    courseId: string;
    chapterId: string;
    isPublished: boolean;
    disabled: boolean
}

const ChapterActions = ({
                            chapterId, disabled, isPublished, courseId
                        }: Props) => {
    const router = useRouter()
    const [isLoading, setIsLoading] = useState(false)

    const onClick = async () => {
        try {
            setIsLoading(true)

            if (isPublished) {
                const res = await fetch(`/api/course/${courseId}/chapters/${chapterId}/unpublish`, {
                    method: "PATCH",
                })
                if (!res.ok) throw new Error("Failed to fetch")
                toast.success(`下架成功`)
                router.refresh()
            } else {
                const res = await fetch(`/api/course/${courseId}/chapters/${chapterId}/publish`, {
                    method: "PATCH",
                })
                if (!res.ok) throw new Error("Failed to fetch")
                toast.success(`发布成功`)
                router.refresh()
            }

            router.refresh()
        } catch (e) {
            toast.error(`Something went wrong`)
        } finally {
            setIsLoading(false)
        }
    }

    const onDelete = async () => {
        try {
            setIsLoading(true)

            const res = await fetch(`/api/course/${courseId}/chapters/${chapterId}`, {
                method: 'DELETE'
            })
            if (!res.ok) throw new Error(`Failed fetch`)
            toast.success(`删除成功`)
            router.refresh()
            router.push(`/learn/teacher/courses/${courseId}`)
        } catch (e) {
            toast.error("Something went wrong");
        } finally {
            setIsLoading(false)
        }
    }

    return (
        <div className={`flex items-center gap-x-2`}>
            <Button
                onClick={onClick}
                disabled={disabled || isLoading}
                size={'sm'}
                variant={'outline'}
            >
                {isPublished ? "Unpublish" : "Publish"}
            </Button>
            <ConfirmModal onConfirm={onDelete}>
                <Button size={'sm'} disabled={isLoading}>
                    <Trash className={`size-4`}/>
                </Button>
            </ConfirmModal>
        </div>
    );
};

export default ChapterActions;